package entity;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 *
 */
public class FeignInterceptor implements RequestInterceptor {
    /**
     * feign执行之前进行拦截
     * @param requestTemplate
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //获取用户令牌
        //通过requestHolder工具类获取request相关变量
        try {
            //使用RequestContextHolder工具获取request相关变量
            //使用feign调用,熔断策略默认是线程池隔离,会开启新的线程,需要改成信号量隔离,不会开启新的线程
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                //取出request
                HttpServletRequest request = attributes.getRequest();
                //获取所有头文件信息的key
                Enumeration<String> headerNames = request.getHeaderNames();
                if (headerNames != null) {
                    while (headerNames.hasMoreElements()) {
                        //头文件的key
                        String name = headerNames.nextElement();
                        //头文件的value
                        String value = request.getHeader(name);
                        System.out.println("name=="+name+",value=="+value);
                        //将令牌数据添加到头文件中,使用feign时会传递到下一个微服务
                        requestTemplate.header(name, value);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
